// 数字格式化工具函数
export const formatNumber = (num: number, decimals = 2): string => {
  return num.toFixed(decimals);
};

// 格式化价格
export const formatPrice = (price: number): string => {
  if (price >= 1000) {
    return price.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  }
  return price.toFixed(6);
};

// 格式化成交量
export const formatVolume = (volume: number): string => {
  if (volume >= 1e9) {
    return `$${(volume / 1e9).toFixed(1)}B`;
  }
  if (volume >= 1e6) {
    return `$${(volume / 1e6).toFixed(1)}M`;
  }
  if (volume >= 1e3) {
    return `$${(volume / 1e3).toFixed(1)}K`;
  }
  return `$${volume.toFixed(0)}`;
};

// 格式化百分比
export const formatPercentage = (percentage: number): string => {
  return `${percentage >= 0 ? '+' : ''}${percentage.toFixed(2)}%`;
};

// 格式化时间
export const formatTime = (timestamp: number | string): string => {
  const date = new Date(timestamp);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  });
};

// 颜色工具函数
export const getPriceChangeColor = (change: number, isDark = false) => {
  if (change > 0) {
    return isDark ? 'text-green-400' : 'text-green-600';
  } else if (change < 0) {
    return isDark ? 'text-red-400' : 'text-red-600';
  }
  return isDark ? 'text-gray-400' : 'text-gray-600';
};

// WebSocket 状态
export enum WebSocketStatus {
  CONNECTING = 'connecting',
  CONNECTED = 'connected',
  DISCONNECTED = 'disconnected',
  ERROR = 'error',
}

// 订单类型定义
export interface TokenPair {
  symbol: string;
  name: string;
  price: number;
  change24h: number;
  volume24h: number;
  icon?: string;
}

export interface OrderBookEntry {
  price: number;
  amount: number;
  total: number;
}

export interface CandleData {
  time: number;
  open: number;
  high: number;
  low: number;
  close: number;
  volume: number;
}

export interface Order {
  id: string;
  time: string;
  pair: string;
  type: 'buy' | 'sell';
  orderType: 'limit' | 'market';
  price: number;
  amount: number;
  filled: number;
  total: number;
  status: 'active' | 'filled' | 'cancelled' | 'partial';
}

// 验证函数
export const validateOrder = (orderData: {
  orderType: 'limit' | 'market';
  price?: number;
  amount: string;
  side: 'buy' | 'sell';
  balance: number;
  currentPrice: number;
}): { isValid: boolean; error?: string } => {
  const { orderType, price, amount, side, balance, currentPrice } = orderData;
  
  if (!amount || parseFloat(amount) <= 0) {
    return { isValid: false, error: '数量必须大于0' };
  }

  if (orderType === 'limit' && (!price || price <= 0)) {
    return { isValid: false, error: '价格必须大于0' };
  }

  const numAmount = parseFloat(amount);
  const orderPrice = orderType === 'market' ? currentPrice : (price || 0);
  
  if (side === 'buy') {
    const requiredBalance = numAmount * orderPrice;
    if (requiredBalance > balance) {
      return { isValid: false, error: '余额不足' };
    }
  } else {
    if (numAmount > balance) {
      return { isValid: false, error: '余额不足' };
    }
  }

  return { isValid: true };
};

// 生成模拟数据的工具函数
export const generateMockCandleData = (basePrice: number, count = 100): CandleData[] => {
  const data: CandleData[] = [];
  let currentPrice = basePrice;
  const now = Date.now();
  
  for (let i = count; i >= 0; i--) {
    const time = now - i * 4 * 60 * 60 * 1000; // 4小时间隔
    const open = currentPrice + (Math.random() - 0.5) * 1000;
    const high = open + Math.random() * 500;
    const low = open - Math.random() * 500;
    const close = low + Math.random() * (high - low);
    const volume = Math.random() * 1000000;
    
    data.push({ time, open, high, low, close, volume });
    currentPrice = close;
  }
  
  return data;
};

export const generateMockOrderBook = (basePrice: number): {
  buyOrders: OrderBookEntry[];
  sellOrders: OrderBookEntry[];
} => {
  const buyOrders: OrderBookEntry[] = [];
  const sellOrders: OrderBookEntry[] = [];
  
  // 生成买单 (价格递减)
  let totalBuy = 0;
  for (let i = 0; i < 10; i++) {
    const price = basePrice - (i + 1) * 25;
    const amount = Math.random() * 2 + 0.1;
    totalBuy += amount;
    buyOrders.push({
      price,
      amount,
      total: totalBuy,
    });
  }
  
  // 生成卖单 (价格递增)
  let totalSell = 0;
  for (let i = 0; i < 10; i++) {
    const price = basePrice + (i + 1) * 25;
    const amount = Math.random() * 2 + 0.1;
    totalSell += amount;
    sellOrders.push({
      price,
      amount,
      total: totalSell,
    });
  }
  
  return { buyOrders, sellOrders };
};
